package net.arvin.view;

import net.arvin.mobilebanksystem.R;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LoadingView {
	private static Dialog mProgressDialog;
	private static int mDismissCount = 0;
	private static Context mContext;

	public static void show(final Context context, String message) {
		mContext = context;
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		final View view = inflater.inflate(R.layout.dialog_loading, null);
		mProgressDialog = new Dialog(mContext, R.style.LoadingDialog);
		TextView messageTv = (TextView) view.findViewById(R.id.message);
		messageTv.setText(message);
		mProgressDialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK
						&& event.getAction() == KeyEvent.ACTION_DOWN) {
					if (isShowing()) {
						mProgressDialog.dismiss();
					}
				}
				return false;
			}
		});
		mProgressDialog.setCancelable(false);
		mProgressDialog.setContentView(view, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT));
		if (++mDismissCount > 0 && !mProgressDialog.isShowing()) {
			mProgressDialog.show();
		}
	}

	public static boolean isShowing() {
		if (mProgressDialog != null) {
			return mProgressDialog.isShowing();
		}
		return false;
	}

	public static void dismiss() {
		mProgressDialog.dismiss();
		mDismissCount--;
		if (mDismissCount < 0) {
			mDismissCount = 0;
		}
	}
}
